package com.heima.wemedia.service.interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.wemedia.service.utils.WmThreadLocalUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WebTokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * 前置拦截 -  获取请求头中的  userId , 放入到当前线程中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            //2. 存入线程
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));

            WmThreadLocalUtil.setUser(wmUser);
            return super.preHandle(request, response, handler);
        }
        //没有权限
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(responseResult));

        return false;
    }
    /**
     * 清楚线程中的用户数据
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清楚线程数据
        WmThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
